package net.frcdb.eventmanager;

import java.awt.BorderLayout;
import net.frcdb.eventmanager.api.Fetcher;
import net.frcdb.eventmanager.api.Event;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Font;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import net.frcdb.eventmanager.api.EventEntry;
import net.frcdb.eventmanager.util.Dialog;
import net.frcdb.eventmanager.util.Exporter;

/**
 *
 * @author tim
 */
@Slf4j
public class Editor extends javax.swing.JFrame {

	private static int selectedYear;
	
	@Getter private List<Event> firstEvents;
	@Getter private List<Event> frcdbEvents;
	@Getter private List<EventEntry> candidates;
	
	private EventTableModel model;
	private MergeOptionsPanel optionsPanel;
	
	/**
	 * Creates new form Editor
	 */
	public Editor() {
		initComponents();
	}

	public static int getSelectedYear() {
		return selectedYear;
	}
	
	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        loadingPanel = new javax.swing.JPanel();
        loadButton = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        frcdbUrlField = new javax.swing.JTextField();
        firstUrlField = new javax.swing.JTextField();
        yearSpinner = new javax.swing.JSpinner();
        jLabel1 = new javax.swing.JLabel();
        editorPanel = new javax.swing.JPanel();
        mergeOptionsWrapper = new javax.swing.JPanel();
        tableWrapper = new javax.swing.JPanel();
        tableScroll = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        menu = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        exportItem = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        quitItem = new javax.swing.JMenuItem();
        editMenu = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("FRC-DB Event Manager");
        getContentPane().setLayout(new java.awt.CardLayout());

        loadButton.setText("Load");
        loadButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadButtonActionPerformed(evt);
            }
        });

        jLabel2.setText("FRC-DB Events:");

        jLabel3.setText("FIRST Events:");

        frcdbUrlField.setText(Fetcher.EVENTS_URL);

        firstUrlField.setText(Fetcher.FIRST_EVENTS_URL);

        yearSpinner.setModel(new javax.swing.SpinnerNumberModel(2013, 0, 2013, 1));

        jLabel1.setText("Year");

        javax.swing.GroupLayout loadingPanelLayout = new javax.swing.GroupLayout(loadingPanel);
        loadingPanel.setLayout(loadingPanelLayout);
        loadingPanelLayout.setHorizontalGroup(
            loadingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(loadingPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(loadingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, loadingPanelLayout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(loadButton))
                    .addGroup(loadingPanelLayout.createSequentialGroup()
                        .addGroup(loadingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(loadingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(frcdbUrlField)
                            .addComponent(firstUrlField)
                            .addGroup(loadingPanelLayout.createSequentialGroup()
                                .addComponent(yearSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 855, Short.MAX_VALUE)))))
                .addContainerGap())
        );
        loadingPanelLayout.setVerticalGroup(
            loadingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, loadingPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(loadingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(frcdbUrlField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(loadingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(firstUrlField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(loadingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(yearSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 482, Short.MAX_VALUE)
                .addComponent(loadButton)
                .addContainerGap())
        );

        getContentPane().add(loadingPanel, "card2");

        mergeOptionsWrapper.setBorder(javax.swing.BorderFactory.createTitledBorder("Merge Options"));
        mergeOptionsWrapper.setLayout(new java.awt.BorderLayout());

        tableWrapper.setBorder(javax.swing.BorderFactory.createTitledBorder("Event Candidates"));

        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tableScroll.setViewportView(table);

        javax.swing.GroupLayout tableWrapperLayout = new javax.swing.GroupLayout(tableWrapper);
        tableWrapper.setLayout(tableWrapperLayout);
        tableWrapperLayout.setHorizontalGroup(
            tableWrapperLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(tableScroll, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 795, Short.MAX_VALUE)
        );
        tableWrapperLayout.setVerticalGroup(
            tableWrapperLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(tableScroll, javax.swing.GroupLayout.DEFAULT_SIZE, 562, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout editorPanelLayout = new javax.swing.GroupLayout(editorPanel);
        editorPanel.setLayout(editorPanelLayout);
        editorPanelLayout.setHorizontalGroup(
            editorPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(editorPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(tableWrapper, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(mergeOptionsWrapper, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        editorPanelLayout.setVerticalGroup(
            editorPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(editorPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(editorPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tableWrapper, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(mergeOptionsWrapper, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        getContentPane().add(editorPanel, "card3");

        fileMenu.setText("File");

        exportItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        exportItem.setText("Export");
        exportItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exportItemActionPerformed(evt);
            }
        });
        fileMenu.add(exportItem);
        fileMenu.add(jSeparator1);

        quitItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
        quitItem.setText("Quit");
        fileMenu.add(quitItem);

        menu.add(fileMenu);

        editMenu.setText("Edit");
        menu.add(editMenu);

        setJMenuBar(menu);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadButtonActionPerformed
        try {
			loadEvents(frcdbUrlField.getText(), firstUrlField.getText());
			mergeEvents();
			
			model = new EventTableModel(candidates);
			table.getSelectionModel().addListSelectionListener(selectionListener);
			table.setDefaultRenderer(Object.class, renderer);
			table.setModel(model);
			
			selectedYear = (Integer) yearSpinner.getValue();
			
			((CardLayout) getContentPane().getLayout()).next(getContentPane());
		} catch (Exception ex) {
			log.error("Couldn't load events", ex);
		}
    }//GEN-LAST:event_loadButtonActionPerformed

    private void exportItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportItemActionPerformed
        JFileChooser f = new JFileChooser();
		f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		if (f.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
			Exporter e = new Exporter();
			try {
				e.export(candidates, f.getSelectedFile());
			} catch (Exception ex) {
				log.error("Export failed", ex);
				Dialog.error(this, "Export failed: " + ex.getMessage());
			}
		}
    }//GEN-LAST:event_exportItemActionPerformed

	public void loadEvents(String frcdbUrl, String firstUrl) throws IOException {
		frcdbEvents = Fetcher.fetchEvents(new URL(frcdbUrl));
		firstEvents = Fetcher.fetchFirstEvents(new URL(firstUrl));
	}

	public void mergeEvents() {
		candidates = new ArrayList<EventEntry>();
		
		for (Event firstEvent : firstEvents) {
			Event frcdbEvent = getFrcdbEventById(firstEvent.getIdentifier());
			
			candidates.add(new EventEntry(frcdbEvent, firstEvent));
		}
	}
	
	public Event getFrcdbEvent(String shortName) {
		for (Event e : frcdbEvents) {
			if (e.getShortName().equalsIgnoreCase(shortName)) {
				return e;
			}
		}
		
		return null;
	}
	
	public Event getFrcdbEventById(String id) {
		for (Event e : frcdbEvents) {
			if (e.getIdentifier().equalsIgnoreCase(id)) {
				return e;
			}
		}
		
		return null;
	}
	
	public JTable getTable() {
		return table;
	}
	
	public void showOptionsPanel(EventEntry entry) {
		clearOptionsPanel();
		
		optionsPanel = new MergeOptionsPanel(this, entry);
		mergeOptionsWrapper.add(optionsPanel, BorderLayout.CENTER);
		mergeOptionsWrapper.validate();
		
	}
	
	public void clearOptionsPanel() {
		mergeOptionsWrapper.removeAll();
	}
	
	private ListSelectionListener selectionListener = new ListSelectionListener() {

		public void valueChanged(ListSelectionEvent e) {
			if (e.getValueIsAdjusting()) {
				return;
			}
			
			 // the selection event gives bad row values
			int row = table.getSelectedRow();
			EventEntry entry = candidates.get(row);
			log.info("Selected: " + entry.getName());
			showOptionsPanel(entry);
		}
	};
	
	private TableCellRenderer renderer = new DefaultTableCellRenderer() {

		@Override
		public Component getTableCellRendererComponent(
				JTable table, Object value, boolean isSelected,
				boolean hasFocus, int row, int column) {
			EventEntry entry = candidates.get(row);
			
			Component c = super.getTableCellRendererComponent(
					table, value, isSelected, hasFocus, row, column);
			
			if (!(c instanceof JLabel)) {
				// we only care about labels
				return c;
			}
			
			JLabel l = (JLabel) c;
			
			// bold new events
			if (entry.getFrcdbEvent() == null) {
				l.setFont(l.getFont().deriveFont(Font.BOLD));
			}
			
			return l;
		}
		
	};
	
	private TableCellRenderer checkboxRenderer = new TableCellRenderer() {

		public Component getTableCellRendererComponent(
				JTable table, Object value, boolean isSelected,
				boolean hasFocus, final int row, final int column) {
			final JCheckBox cb = new JCheckBox();
			cb.setSelected((Boolean) value);
			
			cb.addChangeListener(new ChangeListener() {

				public void stateChanged(ChangeEvent e) {
					if (model.isCellEditable(row, column)) {
						model.setValueAt(cb.isSelected(), row, column);
					} else {
						cb.setSelected((Boolean) model.getValueAt(row, column));
					}
				}
				
			});
			
			return cb;
		}
	};
	
	private TableCellEditor checkboxEditor = new TableCellEditor() {

		
		public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
			throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
		}

		public Object getCellEditorValue() {
			return null;
		}

		public boolean isCellEditable(EventObject anEvent) {
			throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
		}

		public boolean shouldSelectCell(EventObject anEvent) {
			throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
		}

		public boolean stopCellEditing() {
			return true;
		}

		public void cancelCellEditing() {
			// do nothing
		}

		public void addCellEditorListener(CellEditorListener l) {
			throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
		}

		public void removeCellEditorListener(CellEditorListener l) {
			throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
		}
	};
	
	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {
		/* Set the Nimbus look and feel */
		//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
		 * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
		 */
		try {
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (ClassNotFoundException ex) {
			java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		}
		//</editor-fold>

		/* Create and display the form */
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new Editor().setVisible(true);
			}
		});
	}
	
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu editMenu;
    private javax.swing.JPanel editorPanel;
    private javax.swing.JMenuItem exportItem;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JTextField firstUrlField;
    private javax.swing.JTextField frcdbUrlField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JButton loadButton;
    private javax.swing.JPanel loadingPanel;
    private javax.swing.JMenuBar menu;
    private javax.swing.JPanel mergeOptionsWrapper;
    private javax.swing.JMenuItem quitItem;
    private javax.swing.JTable table;
    private javax.swing.JScrollPane tableScroll;
    private javax.swing.JPanel tableWrapper;
    private javax.swing.JSpinner yearSpinner;
    // End of variables declaration//GEN-END:variables
}
